package com.research.controller;
import com.research.common.R;
import com.research.service.ResearchProjectService;
import com.research.service.StorageService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;


//都是restful风格
@RestController
@Slf4j
@RequestMapping("/")
public class ConmmonController {

    @Autowired
    private StorageService storageService;
    private ResearchProjectService researchProjectService;

    @Value("${upload.accessPath}")
    private String accessPath;
    @Value("${upload.localPath}")
    private String localPath;
    //上传文件的功能
    @PostMapping(value = "/upload")
    //访问一个链接，http请求所有信息会放在request里面，所有的返回放在response
    //所以response需要返回一个json格式
    public R upload(HttpServletRequest request, HttpServletResponse response){
        //处理跨域问题
//        response.setHeader ("Access-Control-Allow-Origin", "*");
        //我们要怎么进行这个请求呢
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)  request;
        //通过multipartRequest获取文件
        //这个file要和我们在body里面填入的key的命名保持一致
        MultipartFile file=multipartRequest.getFile("file");
        // 判断上传的文件是否为空
//        boolean isEmpty = file.isEmpty();
//        if (isEmpty) {
//            throw new CustomException("上传失败！上传的文件为空！");
//        }

        //现在我们就可以获取到文件的信息，比如我们获取文件的名称
        String fileName=file.getOriginalFilename();
        log.info("文件的名称是："+fileName);

        //一般文件名称fileName被计算机取出来还会加上time的信息
        storageService.save(file,fileName,localPath);


        //如果你直接自己拼接，计算机是不知道你要访问的路径在那的，需要关联
        return R.success("http://localhost:8080"+accessPath+fileName);
    }
}